import React, { useRef, useState } from 'react';
import {  MinusOutlined } from '@ant-design/icons';
import {  PageContainer,  ProTable,} from '@ant-design/pro-components';
import { Button, message, Image, Popconfirm } from 'antd';
import _ from '@/assets/utils';
import MODEL_API from '@/services/model';
import styled from 'styled-components';
import { history, useSearchParams, useModel, Helmet } from '@umijs/max';
const RightStyle = styled.div`
    .ant-pro-table-list-toolbar-right   {
  margin-right: 1100px;
}
`;
const Order = function Order() {
    const columns = [{
        title: '订单号',
        dataIndex: 'orderNo',
        width: '17.5%',
    }, {
        title: "订单总价",
        dataIndex: 'totalPrice',
        width: '15%',
        search: false
    }, {
        title: '订单状态',
        dataIndex: 'orderStatus',
        width: '15%',
        valueEnum: {
            0: {
                text: '待支付',
                status: 0,
            },
            1: {
                text: '已支付',
                status: 1,
            },
            2: {
                text: '配货完成',
                status: 2,
            },
            3: {
                text: '出库成功',
                status: 3,
            },
            4: {
                text: '交易成功',
                status: 4,
            },
            '-1': {
                text: '手动关闭',
                status: '-1',
            },
            '-2': {
                text: '超时关闭',
                status: '-2',
            },
            '-3': {
                text: '商家关闭',
                status: '-3',
            }
        },

    }, {
        title: '支付方式',
        dataIndex: 'payType',
        width: '15%',
        search: false,
        render: (_, record) => {
            let { payType } = record;
            if (payType === 0) {
                return '未支付'
            } else if (payType === 1) {
                return '微信支付'
            } else if (payType === 2) {
                return '支付宝支付'
            }
        }
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        with: '22.5%',
        search: false,
        render: (dom) => {
            if (!dom) return '--';
            return _.formatTime(dom, '{0}-{1}-{2} {3}:{4}:{5}');
        }
    }, {
        title: '操作',
        with: '15%',
        search: false,
        render: (_, record) => {
            let { orderId, orderStatus } = record;
            let num = [0, 1, 2, 3];
            let num2 = [4, -1, -3];
            return [
                orderStatus === 1 ?
                    <Popconfirm key="finish" title="确定配货完成吗？"
                        onConfirm={() => {
                            checkF([orderId]);
                        }}>
                        <a href="#" style={{
                            display: 'inlineBlock',
                            paddingRight: '15px'
                        }}>配货完成</a>
                    </Popconfirm> : '',
                orderStatus === 2 ?
                    <Popconfirm key="check" title="确定要出库吗？"
                        onConfirm={() => {
                            checkOk([orderId]);
                        }}>
                        <a href="#" style={{
                            display: 'inlineBlock',
                            paddingRight: '15px'
                        }}>出库</a>
                    </Popconfirm> : '',
                num.map(item => {
                    return orderStatus === item ?
                        <Popconfirm key="delete" title="确定要关闭订单吗？"
                            onConfirm={() => {
                                orderClose([orderId]);
                            }}>
                            <a href="#" style={{
                                display: 'inlineBlock',
                                paddingRight: '15px'
                            }}>关闭订单</a>
                        </Popconfirm> : ''
                }),
                <Button key="update" type="link" style={{ paddingLeft: 0 }}
                    // 路由跳转+传参赋值
                    onClick={() => {
                        history.push({
                            pathname: '/modulars/order_detail',
                            query: {
                              id: orderId
                            }
                          });
                    }}>
                    订单详情
                </Button>,
                num2.map(item => {
                    return orderStatus === item ?
                        <Button key='_' style={{ display: 'none' }} >订单详情</Button> : ''
                }),
            ];
        }
    }]
    const [selectList, setSelectList] = useState([]),//存批量选中的id
        tableIns = useRef(); //刷新页面的
    /* 表格数据的处理 */
    const queryTableData = async ({ pageSize, current, orderNo, orderStatus }) => {

        let tableData = [],
            total = 0;
        try {
            let { resultCode, data } = await MODEL_API.orderList(current, pageSize, orderNo, orderStatus);
            if (+resultCode === 200) {
                total = +data.totalCount;
                tableData = data.list;
            }
        } catch (_) { }
        // 不论请求成功还是失败，都让表格进行渲染
        return {
            success: true,
            data: tableData,
            total
        };
    };

/* 关闭操作 */
const orderClose = async (ids) => {
    try {
        let { resultCode } = await MODEL_API.orderDown(ids);
        if (+resultCode !== 200) {
            message.error("测试环境不支持该操作，可自行搭建后端API服务");
            return;
        }
        message.success('恭喜您，关闭成功！');
        tableIns.current.reload();
    } catch (_) { }
};

/* 出库成功 */
const checkOk = async (ids) => {
    try {
        let { resultCode } = await MODEL_API.checkOut(ids);
        if (+resultCode !== 200) {
            message.error("订单的状态不是支付成功或配货完成无法执行出库操作");
            return;
        }
        message.success('出库成功！');
        tableIns.current.reload();
    } catch (_) { }
};

/* 配货完成 */
const checkF = async (ids) => {
    try {
        let { resultCode } = await MODEL_API.checkDone(ids);
        if (+resultCode !== 200) {
            message.error("订单的状态不是支付成功无法执行配货完成操作");
            return;
        }
        message.success('配货完成！');
        tableIns.current.reload();
    } catch (_) { }
};


    return <PageContainer>
        <RightStyle>
        <ProTable
            request={queryTableData}
            columns={columns}
            // search={{
            //     optionRender: false,
            //     collapsed: false,
            //   }}
            options={{
                density: false,
                reload: false,
                setting: false
            }}
            pagination={{
                pageSize: 10,
                hideOnSinglePage: false,
                showTotal: false,
                showQuickJumper: false,
                showSizeChanger: false
            }}
            toolBarRender={() => {
                return [
                    <Button key="relieve" type="primary"
                        onClick={async() => {  await checkF(selectList) }}>
                        <MinusOutlined /> 配货完成
                    </Button>,
                    <Button key="relieve" type="primary"
                        onClick={async () => {
                            await checkOk(selectList) }}>
                        <MinusOutlined /> 出库
                    </Button>,
                    <Button key="prohibit" type="primary" danger
                    onClick={async () => {
                        if (selectList.length === 0) {
                            message.warning('请至少选择一项进行删除~');
                            return;
                        }
                        await handleRemove(selectList);
                    }}>
                        <MinusOutlined /> 关闭订单
                    </Button>
                ];
            }}
            actionRef={tableIns}
            rowKey="orderNo"
            rowSelection={{
                onChange: (selectedIds,selectedRows) =>{
                    selectedRows= selectedRows.map(item=>{
                        return item.orderId
                    })
                
                    setSelectList(selectedRows);
                    
                } 
            }}
        />
        </RightStyle>
    </PageContainer>;
};
export default Order;